package com.edushare.common.dao.academics.grades;

import java.util.List;

import com.edushare.common.dao.CurriculumDAO;
import com.edushare.common.orm.ORMInterface;
import com.edushare.common.vo.Courses;
import com.edushare.common.vo.Curricula;

public class CreditManager {
	Curricula curricula = null;
	ORMInterface orm = null;

	public CreditManager(Curricula curr, ORMInterface orm) {
		this.curricula = curr;
		this.orm = orm;
	}

	public int getMinCreditsForSem(int semesterNum) {
		return getMandatoryCourseCredits(semesterNum)
				+ getMinOptionalCourseCredits(semesterNum);
	}
	
	public int getMaxCreditsForSem(int semesterNum) {
		return getMandatoryCourseCredits(semesterNum)
				+ getMaxOptionalCourseCredits(semesterNum);
	}

	public int getMinTotalCredits() {
		int semesters = curricula.getTotalSemester();
		int credits = 0;
		for (int i = 0; i < semesters; i++) {
			credits += getMinCreditsForSem(i);
		}
		return credits;
	}
	
	public int getMaxTotalCredits() {
		int semesters = curricula.getTotalSemester();
		int credits = 0;
		for (int i = 0; i < semesters; i++) {
			credits += getMaxCreditsForSem(i);
		}
		return credits;
	}

	private int getMandatoryCourseCredits(int semesterNum) {
		CurriculumDAO cDAO = new CurriculumDAO(orm);
		int credits = 0;
		List<Courses> manCourses = cDAO.getMandatoryCourses(curricula,
				semesterNum);
		for (Courses c : manCourses) {
			credits += c.getCredits();
		}
		return credits;
	}

	private int getMinOptionalCourseCredits(int semesterNum) {
		CurriculumDAO cDAO = new CurriculumDAO(orm);
		int numElectives = cDAO.getNumElectives(curricula, semesterNum);
		int credits = 0;
		for (int i = 0; i < numElectives; i++) {
			List<Courses> electiveSet = cDAO.getElectiveCourses(curricula,
					semesterNum, i);
			int minCredits = 1000;
			for (Courses c1 : electiveSet) {
				if (minCredits > c1.getCredits())
					minCredits = c1.getCredits();
			}
			credits += minCredits;
		}
		return credits;
	}
	
	private int getMaxOptionalCourseCredits(int semesterNum) {
		CurriculumDAO cDAO = new CurriculumDAO(orm);
		int numElectives = cDAO.getNumElectives(curricula, semesterNum);
		int credits = 0;
		for (int i = 0; i < numElectives; i++) {
			List<Courses> electiveSet = cDAO.getElectiveCourses(curricula,
					semesterNum, i);
			int maxCredits = 0;
			for (Courses c1 : electiveSet) {
				if (maxCredits < c1.getCredits())
					maxCredits = c1.getCredits();
			}
			credits += maxCredits;
		}
		return credits;
	}
}
